//
//  ZJVidoViewTabViewController.m
//  ZhongWangYuanApp
//
//  Created by ZJ on 2018/6/4.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "ZJVidoViewTabViewController.h"
#import "LPVideoViewTableGGBPlayListViewController.h"
#import "LPVideoViewTableGGBClassIntroViewController.h"
#import "LPVideoViewTableGGBStudyClassViewController.h"
#import "GTPageControllModel.h"
#import "ZJCourseNameView.h"
#import "ZJCourseCommentAndCollectView.h"
#import "PLVVodSkinPlayerController.h"
#import "AppDelegate.h"
#import "YBCommentVideoView.h"
#import "ZJSelectionsMdel.h"
#import "YBObjectIntroductionModel.h"
#import "YBClassProgressViewController.h"
#import "KYVedioPlayer.h"
@interface ZJVidoViewTabViewController ()<ZJCourseNameViewDelegate,ZJCourseCommentAndCollectViewDelegate,YBCommentVideoViewDelegate,KYVedioPlayerDelegate>
{
    BOOL _isComment;/**< 是否评价 */
    NSTimer *_timer;/**< 定时器 */
    BOOL _isSwithVideo;/**< 本地记录是否是视频播放 */
    double _changeVideoType_Time;/**< 记录同一课程的音、视频切换的时间，不同课程的切换回变成0 */
    NSString *_UUID;/**< 记录课程的UUID */
    NSString *_studetailcount;/**< 随currentID变化，当currentID发生变化的第一次提交数据时为0，数据成功后变成1，后面一直是1，直到该门课程播放完成或者发生切课。 */
}
/** 播放视图 */
@property (nonatomic, strong) UIView *playView;
/** 课程名称及课程评分收藏情况 */
@property (nonatomic, strong) ZJCourseNameView *courseNameView;
/** 下方收藏及评价按钮 */
@property (nonatomic, strong) ZJCourseCommentAndCollectView *commentAndCollectView;
/** 保利威视的播放器 */
//@property (nonatomic, strong) PLVVodSkinPlayerController *player;
/** 自己的播放器播放器 */
@property (nonatomic, strong) KYVedioPlayer *player1;
/**< 记录最后播放时间 (视频切换) */
@property (nonatomic, assign) NSTimeInterval laststudytime;
/**    */
@property (strong, nonatomic) GTPageController  *gtPageVc;
/**  播放列表  */
@property (strong, nonatomic) NSArray  *playsArray;
/**  播放列表model  */
@property (strong, nonatomic) NSArray  *playsModelArray;
/** 评论模块 */
@property (nonatomic, strong) YBCommentVideoView *commentVideoView;
/** 保存是否离开这个个页面   yes时自动播放不能播放  */
@property (nonatomic, assign) BOOL isLeaveVC;

@end

@implementation ZJVidoViewTabViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.model.classOrCourse integerValue] == 1) {
        self.classId = self.model.ID;
    }else{
        self.classId = @"";
    }
    self.titlelabel.text = @"详情";
    self.isLeaveVC = NO;
    _isComment = NO;
    _isSwithVideo = YES;
    [self getChangePropsFromChangeCourse];
    [self getData];
    [self setupUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNewVideoID:) name:Notification_Push_VideoID object:nil];
    //支持后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.player1.isPlaying) {
       [self.player1 pause];
    }
    [_timer invalidate];
    self.isLeaveVC = YES;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [self netWorking_video_begin];
    //清楚后台播放标记
    [ToolClass setBackPlayInfoWithTitle:@"" singer:@"" imageName:@"" totalTime:0 alreadyTime:0];
}

#pragma mark - 第一次请求页面数据
- (void)getData{
    NSString *coursewareid = @"";
    NSString *classid = @"";
    if ([self.model.classOrCourse integerValue] == 1) {
        classid = self.model.ID;
    }else{
        coursewareid = self.model.ID;
    }
    __weak typeof(self) weakSelf = self;
     [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    [LPRequestManager request_getCoursewareVideoplayWithcoursewareid:coursewareid classid:classid enableplaylist:@"true" successBlock:^(id object) {
        NSString *code = [object objectForKey:@"code"];
        if ([code integerValue] == 1) {
            LPZWYChooseClassClassModel *model = [LPZWYChooseClassClassModel yy_modelWithJSON:[[object objectForKey:@"data"] objectForKey:@"currentcourseware"]];
            weakSelf.playsArray = [[object objectForKey:@"data"] objectForKey:@"playlist"];
            weakSelf.playsModelArray = [NSArray yy_modelArrayWithClass:[LPZWYChooseClassClassModel class] json:weakSelf.playsArray];
            
            NSString * classOrCourseString = [NSString stringWithFormat:@"%@" , weakSelf.model.classOrCourse];
            NSString * classIdString = [NSString stringWithFormat:@"%@" , weakSelf.model.ID];
            ///课程没有值的话默认取列表第一个
            weakSelf.model = model ? model : weakSelf.playsModelArray.firstObject;
            
            weakSelf.model.classOrCourse = classOrCourseString;
            weakSelf.model.classid = classIdString;
            [weakSelf layoutUI];
            [weakSelf initData];
            [weakSelf getFristPlayerVideoIndex];
            [YJProgressHUD zj_MainThead_hide];
        }else{
            [weakSelf netWroking_Error_PopVC];
        }
    } failBlock:^(id object) {
        [weakSelf netWroking_Error_PopVC];
    }];
}
///初始化接口请求失败就返回上个界面
- (void)netWroking_Error_PopVC{
    [YJProgressHUD zj_MainThead_showMessage:@"网络请求失败" inView:self.view];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[ToolClass getMainNavigationController] popViewControllerAnimated:YES];
    });
}

#pragma mark - 第一次得到播放的视频
///拿到当前课程对列表页面赋值
- (void)getFristPlayerVideoIndex{
    __weak typeof(self) weakSelf = self;
    NSArray *array = [self.playsModelArray copy];
    [array enumerateObjectsUsingBlock:^(LPZWYChooseClassClassModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.ID isEqualToString:self.model.ID]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Receive_VideoID_ONE object:@{@"Model":obj}];
            return ;
        }
    }];
}
#pragma mark - 播放完成自动切换视频
- (void)playerOver{
    __weak typeof(self) weakSelf = self;
    __block NSInteger flag = 0;
    [self.playsModelArray enumerateObjectsUsingBlock:^(LPZWYChooseClassClassModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.ID isEqualToString:weakSelf.model.ID]) {
            if (weakSelf.playsArray.count > idx + 1) {//不是最后一个
                flag = idx + 1;
            }else{//是最后一个   也发送改变cell的完成度
               [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Receive_VideoID object:@{@"Model":obj}];
                flag = idx;
            }
        }
    }];
    if (flag > 0) {//发生了变换
        if (flag == self.playsModelArray.count - 1) {//当前播放完成的是最后一个
            flag = 0;//转换成第一个视频，进行播放
        }
        LPZWYChooseClassClassModel *nextModel = [LPZWYChooseClassClassModel yy_modelWithJSON:weakSelf.playsArray[flag]];
        weakSelf.model = nextModel;
        [weakSelf initData];
        // 不是最后一个  发送通知改变cell的完成度 并播放下一个视频
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Receive_VideoID object:@{@"Model":nextModel}];
    }
}

#pragma mark - 初始化页面

- (void)setupUI{
    [self.view addSubview:self.playView];
    [self.view addSubview:self.courseNameView];
    [self.view addSubview:self.commentAndCollectView];

    self.playView.sd_layout
    .topSpaceToView(self.navigView, 0)
    .leftEqualToView(self.navigView)
    .widthIs(self.view.width)
    .heightIs(self.view.width / 16 * 9);
    
    self.courseNameView.sd_layout
    .topSpaceToView(self.playView, 0)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0);
    
    self.commentAndCollectView.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view)
    .heightIs(50 * [UIScreen zj_screenHScale]);
}

#pragma mark - 界面
- (void)layoutUI{
    
    self.gtPageVc = [self getDefaultController];
    self.gtPageVc.scrollView.scrollEnabled = NO;
    [self.view addSubview:self.gtPageVc.view];
    [self addChildViewController:self.gtPageVc];
    
    self.gtPageVc.view.sd_layout
    .topSpaceToView(self.courseNameView, 0)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomSpaceToView(self.commentAndCollectView,0);
    
}


#pragma mark - 私有方法
- (GTPageController *)getDefaultController{
    
    LPVideoViewTableGGBPlayListViewController *introduceVC = [LPVideoViewTableGGBPlayListViewController new];
    LPVideoViewTableGGBClassIntroViewController * newsVC = [LPVideoViewTableGGBClassIntroViewController new];
    YBClassProgressViewController *examVC = [YBClassProgressViewController new];
    YBObjectIntroductionModel *first = [YBObjectIntroductionModel new];
    first.dataSouce = self.playsArray;
    
    
    YBObjectIntroductionModel *second = [YBObjectIntroductionModel new];
    second.content = self.model.comment;
    
    YBObjectIntroductionModel *three = [YBObjectIntroductionModel new];
    three.ID = self.model.classid;
    three.issignin = @"1";
    
    NSArray *models = @[];
    NSArray *titles = @[];
    NSArray *viewVcs = @[];
    if ([self.model.classOrCourse integerValue] == 1) {
        models = @[first, second, three];
        titles = @[ @"播放列表", @"课程简介" , @"专题考试"];
        viewVcs = @[[introduceVC class] , [newsVC class] ,[examVC class]];
    }
    else{
        models = @[first, second];
        titles = @[ @"播放列表", @"课程简介"];
        viewVcs = @[[introduceVC class] , [newsVC class]];
    }
    
    
    __weak typeof(self) weakSelf = self;
    __block NSMutableArray *titlesWidth = [NSMutableArray array];
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat width = [NSString sizeOfString:obj font:16 * [UIScreen zj_textFontScale]  width:weakSelf.view.width].width + 12 * [UIScreen zj_screenWScale];
        [titlesWidth addObject:@(width)];
    }];
    
    GTPageController *pageVC = [[GTPageController alloc] initWithViewControllerClasses:viewVcs andTheirTitles:titles];
   
    pageVC.pageAnimatable = YES;
    pageVC.modelArray = models;
    pageVC.itemsWidths = titlesWidth;
    pageVC.postNotification = YES;
    pageVC.Notscroll = YES;
    pageVC.menuBGColor = [UIColor clearColor];
    pageVC.menuViewStyle = GTMenuViewStyleLine;
    pageVC.progressColor = [UIColor themeColor];
    pageVC.titleColorSelected = [UIColor themeColor];
    pageVC.titleColorNormal = [UIColor textGrayColor];
    pageVC.titleSizeNormal = 16 * [UIScreen zj_textFontScale];
    pageVC.titleSizeSelected = 17 * [UIScreen zj_textFontScale];
    pageVC.menuHeight = 50 * [UIScreen zj_screenHScale];
    return pageVC;
}



#pragma mark - 初始化数据
- (void)initData{
    [self getCourseInfo];
    
}
#pragma mark - 初始化数据接口
///课程基本信息
- (void)getCourseInfo{
    
    [YJProgressHUD show:@"" inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    [ZJRequestManager request_getCoursewareInfoWithID:self.model.ID successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSArray *array = [object objectForKey:@"data"];
            self.model = [LPZWYChooseClassClassModel yy_modelWithJSON:array.firstObject];
            [weakSelf initUIFromNetWorkingData];
            [YJProgressHUD hide];
        }
        [YJProgressHUD hide];
    } failBlock:^(id object) {
        [YJProgressHUD hide];
    }];
}


#pragma mark - 根据网络请求的数局来初始化界面
- (void)initUIFromNetWorkingData{
    [self initPlayVideoController1];
    self.courseNameView.model = self.model;
    ///评价
    //已评1，未评0
    if ([self.model.isappraised integerValue] == 0) {
        _isComment = NO;
    }else{
        _isComment = YES;
    }
    [self.commentAndCollectView setCommentButtonIsComment:_isComment model:self.model];
    ///收藏
    if ([self.model.ifcollectedcourse integerValue] == 0) {
        [self.commentAndCollectView setCollectButtonIsCollect:NO];
    }else{
        [self.commentAndCollectView setCollectButtonIsCollect:YES];
    }
    //
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_CourseComment object:@{@"Model":self.model}];
}
#pragma mark - 初始化控制器
//- (void)initPlayVideoController{
//    if (!self.player) {
//        self.player = [[PLVVodSkinPlayerController alloc] initWithNibName:nil bundle:nil];
//        self.player.enableTeaser = YES;
//        self.player.enableBackgroundPlayback = YES;// 是否允许后台播放
//        //隐藏
//        self.player.videoCoverView.hidden = YES;
//        [self.player setVideoCoverViewToBack];
//        [self.player.videoCoverView hiddenViews];
//        [self.player addPlayerOnPlaceholderView:self.playView rootViewController:self];
//    }
//
//    [self.player.videoCoverView setBgImageViewURL:self.model.imagephoto timeString:[NSString stringWithFormat:@"%@",self.model.realduration ? self.model.realduration : @""]];
//    NSString *videoID = @"";
//    if ([self getPayerTypeIsVideoOrVoice]) {//优先播放视频
//        videoID = self.model.teachervideo;
//        self.player.videoCoverView.hidden = YES;
//        [self.courseNameView setVideoPlayType_isVideo:YES];
//    }else{//音频
//        videoID = self.model.audio_url;
//        self.player.videoCoverView.hidden = NO;
//        [self.courseNameView setVideoPlayType_isVideo:NO];
//    }
//
//    __weak typeof(self) weakSelf = self;
//    [PLVVodVideo requestVideoWithVid:videoID completion:^(PLVVodVideo *video, NSError *error) {
//        [weakSelf.player setVideo:video];
//        ///设置播放开始时间
//        [weakSelf netWorking_video_begin];
//    }];
//
//    ///播放结束
//    [self.player setReachEndHandler:^(PLVVodPlayerViewController *player) {
//        NSDictionary *dict = [weakSelf.model yy_modelToJSONObject];
//        [weakSelf netWorking_video_begin_model:[LPZWYChooseClassClassModel yy_modelWithJSON:dict] currentPlaybackTime:weakSelf.player.currentPlaybackTime];
//        [weakSelf getChangePropsFromChangeCourse];
//        [weakSelf playerOver];
//    }];
//    //播放就绪
//    [self.player setPreparedToPlayHandler:^(PLVVodPlayerViewController *player) {
//        [weakSelf.player setStartPlaybackTime:[weakSelf.model.lastplaytime doubleValue] + 1] ;
//        if (!weakSelf.isLeaveVC) {//停留在本页面
//            [weakSelf.player play];
//            [weakSelf initTimer];
//        }
//    }];
//    ///播放状态
//    [self.player setPlaybackStateHandler:^(PLVVodPlayerViewController *player) {
//        if (weakSelf.player.playbackState == PLVVodPlaybackStatePlaying || weakSelf.player.playbackState == PLVVodPlaybackStatePaused) {//播放
//            [ToolClass setBackPlayInfoWithTitle:[NSString string:weakSelf.model.name isNilStringReturnDeftString:@"暂无" ]
//                                         singer:[NSString string:weakSelf.model.teachersname isNilStringReturnDeftString:@"暂无" ]
//                                      imageName:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,weakSelf.model.imagephoto]
//                                      totalTime:0
//                                    alreadyTime:0];
//        }
//    }];
//}

- (void)initPlayVideoController1{
    [self releasePlayer];
    if (!self.player1) {
        CGRect playerFrame = CGRectMake(0, 0, self.playView.width, self.playView.height);
        self.player1 = [[KYVedioPlayer alloc]initWithFrame:playerFrame];
        self.player1.delegate = self;
        //隐藏
        self.player1.videoCoverView.hidden = YES;
        [self.player1 setVideoCoverViewToBack];
        [self.player1.videoCoverView hiddenViews];
        self.player1.closeBtn.hidden = YES;
        self.player1.progressColor = [UIColor whiteColor];
        [self.playView addSubview:self.player1];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NotificationDeviceOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    [self.player1.videoCoverView setBgImageViewURL:self.model.imagephoto timeString:[NSString stringWithFormat:@"%@",self.model.realduration ? self.model.realduration : @""]];
    [self.player1 clearVideoviewerWatchDuration];
    NSString *URLString = @"";
    if ([self getPayerTypeIsVideoOrVoice]) {//视频
        URLString = self.model.teachervideo;
        self.player1.videoCoverView.hidden = YES;
        [self.courseNameView setVideoPlayType_isVideo:YES];
    }else{
        URLString = self.model.audio_url;
         self.player1.videoCoverView.hidden = NO;
        [self.courseNameView setVideoPlayType_isVideo:NO];
    }
        self.player1.URLString = URLString;

    [self.player1 play];
    [self.player1 setStartPlaybackTime:[self.model.lastplaytime doubleValue] + 1];
    [self initTimer];
    [self netWorking_video_begin];
}
/**
 *  注销播放器
 **/
- (void)releasePlayer
{
    [self.player1 resetKYVedioPlayer];
    self.player1 = nil;
}

#pragma mark - 视屏播放相关接口
//自动播放时调用
- (void)netWorking_video_begin{
    [self netWorking_video_begin_model:self.model currentPlaybackTime:self.player1.currentPlaybackTime];
}
///开始 （视频播放完成的时候记录原来的播放时间和model）
- (void)netWorking_video_begin_model:(LPZWYChooseClassClassModel *)model currentPlaybackTime:(NSTimeInterval)currentPlaybackTime {
    __weak typeof(self) weakSelf = self;
    [ZJRequestManager request_getCoursePlayerBeginWithCoursewareid:model.ID courwarestudytime:self.model.studytime successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSDictionary *dict = [object objectForKey:@"data"];
            NSString *pkey = [dict objectForKey:@"pkey"];
            if (pkey.length > 0) {
                 [weakSelf netWorking_video_SaveSchedule_model:model currentPlaybackTime:currentPlaybackTime pkey:pkey];
            }
        }
        
    } failBlock:^(id object) {
        
    }];
}

///保存进度
- (void)netWorking_video_SaveSchedule_model:(LPZWYChooseClassClassModel *)model currentPlaybackTime:(NSTimeInterval)currentPlaybackTime pkey:(NSString *)pkey{
    [ZJRequestManager request_getCoursePlayerSaveScheduleWithCoursewareid:model.ID
                                                                     time:[NSString stringWithFormat:@"%f",currentPlaybackTime]
                                                                     pkey:pkey
                                                            videoDuration:model.realduration
                                                        courwarestudytime:model.studytime
                                                               playerTime:[NSString stringWithFormat:@"%.0f",self.player1.viewerWatchDuration + _changeVideoType_Time]
                                                           coursewarename:model.name
                                                                currentID:_UUID
                                                           studetailcount:_studetailcount classId:self.classId
                                                             successBlock:^(id object) {
         if ([[object objectForKey:@"code"] integerValue] == 1) {//请求成功
             if ([_studetailcount isEqualToString:@"0"]) {
                 _studetailcount = @"1";
             }
         }
     } failBlock:^(id object) {
         
     }];
}

#pragma mark - NSTimer
- (void)initTimer{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(netWorking_video_begin) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        }else{
            [self startTimer];
        }
    });
}
///开始timer
- (void)startTimer{
    dispatch_async(dispatch_get_main_queue(), ^{
    _timer.fireDate = [NSDate distantPast];
    });
}
///暂停timer
- (void)stopTimer{
    dispatch_async(dispatch_get_main_queue(), ^{
    _timer.fireDate = [NSDate distantFuture];
    });
}

- (void)dealloc{
    _timer = nil;
    [self releasePlayer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - ZJCourseNameViewDelegate(视频和音频的切换) 协议方法
- (void)ZJCourseNameViewDelegate_isSwithVideo:(BOOL)isSwithVideo{
    ///记录当前时间
    self.laststudytime = ceil(self.player1.currentPlaybackTime) ;
    _changeVideoType_Time = self.player1.viewerWatchDuration + _changeVideoType_Time;
    if (isSwithVideo) {//播放视频
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:YBUSERINFOMODEL.sessionId];//记录偏好
    }else{//播放音频
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:YBUSERINFOMODEL.sessionId];//记录偏好
    }
    [self initPlayVideoController1];
    [self.player1 play];
    [self.player1 setStartPlaybackTime:self.laststudytime];
    return;
  #pragma mark - 保利威视播放器
//    ///记录当前时间
//    self.laststudytime = ceil(self.player.currentPlaybackTime) ;
//    _changeVideoType_Time = self.player.viewerWatchDuration + _changeVideoType_Time;
//    NSString *videoID = @"";
//    if (isSwithVideo) {//播放视频
//        videoID = self.model.teachervideo;
//        self.player.videoCoverView.hidden = YES;
//        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:YBUSERINFOMODEL.sessionId];//记录偏好
//    }else{//播放音频
//        videoID = self.model.audio_url;
//        self.player.videoCoverView.hidden = NO;
//        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:YBUSERINFOMODEL.sessionId];//记录偏好
//    }
//    __weak typeof(self) weakSelf = self;
//    [PLVVodVideo requestVideoWithVid:videoID completion:^(PLVVodVideo *video, NSError *error) {
//        if (!error) {
//            [weakSelf.player setVideo:video];
//            [weakSelf netWorking_video_begin];
//        }
//    }];
//     ///播放就绪
//    [self.player setPreparedToPlayHandler:^(PLVVodPlayerViewController *player) {
//        if (!weakSelf.isLeaveVC) {//未退出页面
//            [weakSelf.player setStartPlaybackTime:weakSelf.laststudytime];
//            [weakSelf.player play];
//            [weakSelf initTimer];
//        }
//
//    }];
}


#pragma mark - ZJCourseCommentAndCollectViewDelegate(下方收藏和评论按钮) 协议方法
///取消收藏
- (void)ZJCourseCommentAndCollectViewDelegate_cancelCollect{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    NSArray *array = [self getCourseIdArray];
    [ZJRequestManager request_getCoursewareCancelCollectWithCoursewareIdArray:array successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSDictionary *dict = [object objectForKey:@"data"];
            if ([[dict objectForKey:@"result"] integerValue] == 1) {//取消收藏成功
                [YJProgressHUD zj_MainThead_showMessage:@"取消收藏成功" inView:weakSelf.view];
                [weakSelf.commentAndCollectView setCollectButtonIsCollect:NO];
                return ;
            }
        }
        [YJProgressHUD zj_MainThead_showMessage:@"取消收藏失败" inView:weakSelf.view];
    } failBlock:^(id object) {
        [YJProgressHUD zj_MainThead_showMessage:@"取消收藏失败" inView:weakSelf.view];
    }];
}
///收藏
- (void)ZJCourseCommentAndCollectViewDelegate_collect{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
     NSArray *array = [self getCourseIdArray];
    [ZJRequestManager request_getCoursewareCollectWithCoursewareIdArray:array successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            NSDictionary *dict = [object objectForKey:@"data"];
            if ([[dict objectForKey:@"result"] integerValue] == 1) {//收藏成功
                [YJProgressHUD zj_MainThead_showMessage:@"收藏成功" inView:weakSelf.view];
                [weakSelf.commentAndCollectView setCollectButtonIsCollect:YES];
                return ;
            }
        }
        [YJProgressHUD zj_MainThead_showMessage:@"收藏失败" inView:weakSelf.view];
    } failBlock:^(id object) {
        [YJProgressHUD zj_MainThead_showMessage:@"收藏失败" inView:weakSelf.view];
    }];
}
- (NSArray *)getCourseIdArray{
    NSArray *models =  [NSArray yy_modelArrayWithClass:[ZJSelectionsMdel class] json:[self jsonStringToObject:self.model.suitejson]] ;
    if (models.count == 0) {
        return @[];
    }
    __block NSMutableArray *array = [NSMutableArray array];
    [models enumerateObjectsUsingBlock:^(ZJSelectionsMdel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [array addObject:obj.coursewareid];
    }];
    return array;
}
///评论
- (void)ZJCourseCommentAndCollectViewDelegate_comment{
    [self.view addSubview:self.commentVideoView];
}

#pragma mark - YBCommentVideoViewDelegate(评论视图的回调) 协议方法
- (void)ybCommentVideoView:(YBCommentVideoView *)ybCommentVideoView didClickCommitButtonWithDataArray:(NSArray *)dataArray nameArray:(NSArray *)nameArray{
    if ([dataArray containsObject:@"0"]) {//未评价完
        [YJProgressHUD zj_MainThead_showMessage:@"请完整评分" inView:self.view];
        return;
    }
    [ybCommentVideoView removeFromSuperview];
    
    __block NSMutableArray *array = [NSMutableArray array];
    
    [nameArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[NSString stringWithFormat:@"%ld",idx + 1] forKey:@"itemid"];
        [dict setObject:obj forKeyedSubscript:@"itemname"];
        [dict setObject:dataArray[idx] forKeyedSubscript:@"rate"];
        [dict setObject:[NSString stringWithFormat:@"%ld",dataArray.count] forKeyedSubscript:@"max"];
        [dict setObject:@"0" forKeyedSubscript:@"isReadonly"];
        [dict setObject:@"" forKeyedSubscript:@"overStar"];
        [dict setObject:[NSString stringWithFormat:@"%ld",[dataArray[idx] integerValue] * 2] forKeyedSubscript:@"percent"];
        [array addObject:dict];
    }];
    [self comment_NetWroking_dataArray:array];
}
///评分的网络请求
- (void)comment_NetWroking_dataArray:(NSArray *)array{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD zj_MainThead_show:@"" inView:self.view mode:YJProgressModeLoading];
    [YBRequestManager request_ybCommitClassWithClasscourseid:@"" coursewareid:self.model.ID classid:@"" scoreList:array successBlock:^(id object) {
        if ([[object objectForKey:@"code"] integerValue] == 1) {
            [YJProgressHUD zj_MainThead_showMessage:@"评分成功" inView:weakSelf.view];
            [weakSelf.commentAndCollectView setCommentButtonIsComment:YES model:weakSelf.model];
            return ;
        }
        [YJProgressHUD zj_MainThead_showMessage:@"评分失败" inView:weakSelf.view];
    } failBlock:^(id object) {
        [YJProgressHUD zj_MainThead_showMessage:@"评分失败" inView:weakSelf.view];
    }];
}

#pragma mark - 接受通知
- (void)getNewVideoID:(NSNotification *)Info{
    NSDictionary *dict = Info.object;
    NSString *videoID = [dict objectForKey:@"videoID"];
    NSArray *modelArray = [dict objectForKey:@"Array"];
    if (videoID.length > 0) {//切换播放视频
        self.model.ID = videoID;
        [self.player1 pause];
        [self getChangePropsFromChangeCourse];
        [self initData];
    }
    if (modelArray.count > 0) {//删除课程
        self.playsModelArray = [modelArray copy];
        [self getFristPlayerVideoIndex];
    }
}

#pragma mark - 后台播放控制
-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type==UIEventTypeRemoteControl) {
        
        if (event.subtype==UIEventSubtypeRemoteControlPlay) {
            //播放
            [self.player1 play];
        }
        if (event.subtype==UIEventSubtypeRemoteControlPause) {
            //暂停
            [self.player1 pause];
        }
    }
}

#pragma mark - 判断课程优先 播放视频还是音频
///判断这个课程优先播放视频还是音频  yes是视频  NO是音频
- (BOOL)getPayerTypeIsVideoOrVoice{
    if ([VIDEO_TYPE isEqualToString:@"1"]) {//优先播放音频
        if (self.model.audio_url) {
            return NO;
        }else{
            return YES;
        }
    }else{//优先播放视频
        if (self.model.teachervideo) {
            return YES;
        }else{
            return NO;
        }
    }
}
#pragma mark - 切换课程需要改变的值
- (void)getChangePropsFromChangeCourse{
    _changeVideoType_Time = 0.0;
    _UUID = [ToolClass createUUIDString];
    _studetailcount = @"0";
}

#pragma mark - 自定义播放器的 屏幕旋转
-(void)NotificationDeviceOrientationChange:(NSNotification *)notification{
    if (self.player1 == nil|| self.player1.superview==nil || !self.player1.videoCoverView.hidden){
        return;
    }
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortraitUpsideDown:{
            //            NSLog(@"第3个旋转方向---电池栏在下");
        }
            break;
        case UIInterfaceOrientationPortrait:{
            //            NSLog(@"第0个旋转方向---电池栏在上");
            if (self.player1.isFullscreen) {
                [self setNeedsStatusBarAppearanceUpdate];
                [self.player1 showSmallScreenWithPlayer:self.player1 withFatherView:self.view withFrame:self.playView.frame];
            }
        }
            break;
        case UIInterfaceOrientationLandscapeLeft:{
            //            NSLog(@"第2个旋转方向---电池栏在左");
            self.player1.isFullscreen = YES;
            [self setNeedsStatusBarAppearanceUpdate];
            [self.player1 showFullScreenWithInterfaceOrientation:interfaceOrientation player:self.player1 withFatherView:self.view];
        }
            break;
        case UIInterfaceOrientationLandscapeRight:{
            //            NSLog(@"第1个旋转方向---电池栏在右");
            self.player1.isFullscreen = YES;
            [self setNeedsStatusBarAppearanceUpdate];
            [self.player1 showFullScreenWithInterfaceOrientation:interfaceOrientation player:self.player1 withFatherView:self.view];
        }
            break;
        default:
            break;
    }
}
#pragma mark - 自定义播放器的 协议方法
//点击全屏按钮代理方法
-(void)kyvedioPlayer:(KYVedioPlayer *)kyvedioPlayer clickedFullScreenButton:(UIButton *)fullScreenBtn{
    if (!self.player1.videoCoverView.hidden) {
        return;
    }
    if (fullScreenBtn.selected) {
        self.player1.isFullscreen = YES;
        [self setNeedsStatusBarAppearanceUpdate];
        [self.player1 showFullScreenWithInterfaceOrientation:UIInterfaceOrientationLandscapeLeft player:self.player1 withFatherView:self.view];
    }else{
        [self setNeedsStatusBarAppearanceUpdate];
        [self.player1 showSmallScreenWithPlayer:self.player1 withFatherView:self.view withFrame:self.playView.frame];
    }
}
//点击播放暂停按钮代理方法
-(void)kyvedioPlayer:(KYVedioPlayer *)kyvedioPlayer clickedPlayOrPauseButton:(UIButton *)playOrPauseBtn{
    if (!playOrPauseBtn.isSelected) {//播放
        [self initTimer];
        [ToolClass setBackPlayInfoWithTitle:[NSString string:self.model.name isNilStringReturnDeftString:@"暂无" ]
                                                  singer:[NSString string:self.model.teachersname isNilStringReturnDeftString:@"暂无" ]
                                               imageName:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,self.model.imagephoto]
                                               totalTime:0
                                             alreadyTime:0];
    }else{//暂停
        [self stopTimer];
    }
}
//播放完毕的代理方法
-(void)kyplayerFinishedPlay:(KYVedioPlayer *)kyvedioPlayer{
    [self.player1 pause];
    NSDictionary *dict = [self.model yy_modelToJSONObject];
    [self netWorking_video_begin_model:[LPZWYChooseClassClassModel yy_modelWithJSON:dict] currentPlaybackTime:self.player1.currentPlaybackTime];
    [self getChangePropsFromChangeCourse];
    [self playerOver];
}


#pragma mark - Getters
- (UIView *)playView{
    if (_playView == nil){
        _playView = [UIView new];
    }
    return _playView;
}
- (ZJCourseNameView *)courseNameView{
    if (_courseNameView == nil){
        _courseNameView = [ZJCourseNameView new];
        _courseNameView.delegate = self;
    }
    return _courseNameView;
}
- (ZJCourseCommentAndCollectView *)commentAndCollectView{
    if (_commentAndCollectView == nil){
        _commentAndCollectView = [ZJCourseCommentAndCollectView new];
        _commentAndCollectView.delelgate = self;
    }
    return _commentAndCollectView;
}
- (YBCommentVideoView *)commentVideoView{
    if (_commentVideoView == nil){
        _commentVideoView = [[YBCommentVideoView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) titleArray:@[@"观点正确",@"表达流畅",@"内容丰富",@"授课认真",@"形象生动"]];
        _commentVideoView.delegate = self;
    }
    return _commentVideoView;
}
@end
